import tkinter as tk
from tkinter import ttk, filedialog, messagebox
from PIL import Image, ImageTk
import sqlite3
import os
from datetime import datetime
import glob
from viewer import *


class MainViewer:
    
    def __init__(self, root):
        self.root = root
        self.root.title("漫画管理工具")
        self.root.geometry("1200x800")
        self.root.configure(bg="#2c3e50")
        
        # 初始化数据库
        self.init_db()
        
        # 创建界面
        self.create_ui()
        
        # 加载漫画数据
        self.current_page = 1
        self.per_page = 20
        self.selected_comics = set()
        self.load_comics()

    def init_db(self):
        self.conn = sqlite3.connect('comic_manager.db')
        self.cursor = self.conn.cursor()
        
        # 创建漫画表
        self.cursor.execute('''
            CREATE TABLE IF NOT EXISTS comics (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                name TEXT NOT NULL,
                folder_path TEXT NOT NULL,
                cover_path TEXT,
                created_at DATETIME DEFAULT CURRENT_TIMESTAMP
            )
        ''')
        
        # 创建标签表
        self.cursor.execute('''
            CREATE TABLE IF NOT EXISTS tags (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                name TEXT NOT NULL UNIQUE
            )
        ''')
        
        # 创建漫画标签关联表
        self.cursor.execute('''
            CREATE TABLE IF NOT EXISTS comic_tags (
                comic_id INTEGER,
                tag_id INTEGER,
                tag_name TEXT,
                PRIMARY KEY (comic_id, tag_id),
                FOREIGN KEY (comic_id) REFERENCES comics(id),
                FOREIGN KEY (tag_id) REFERENCES tags(id)
            )
        ''')
        
        self.conn.commit()


    def create_ui(self):
        # 顶部栏
        top_frame = tk.Frame(self.root, bg="#34495e", height=40)
        top_frame.pack(fill="x", padx=10, pady=10)
        
        import_btn = tk.Button(top_frame, text="导入漫画", command=self.import_comics, 
                             bg="#3498db", fg="white", font=("Arial", 10, "bold"))
        import_btn.pack(side="left", padx=5, pady=5)
        
        # 工具栏
        toolbar = tk.Frame(self.root, bg="#34495e", height=40)
        toolbar.pack(fill="x", padx=10, pady=(0, 10))
        
        search_frame = tk.Frame(toolbar, bg="#34495e")
        search_frame.pack(side="left", padx=5)
        
        search_options = ["按名称", "按标签"]
        self.search_var = tk.StringVar(value=search_options[0])
        search_dropdown = ttk.Combobox(search_frame, textvariable=self.search_var, 
                                      values=search_options, width=8, state="readonly")
        search_dropdown.pack(side="left", padx=(0, 5))
        
        self.search_entry = tk.Entry(search_frame, width=30)
        self.search_entry.pack(side="left", padx=(0, 5))
        
        search_btn = tk.Button(search_frame, text="查询", command=self.search_comics,
                             bg="#2ecc71", fg="white")
        search_btn.pack(side="left")
        
        # 批量操作按钮
        batch_frame = tk.Frame(toolbar, bg="#34495e")
        batch_frame.pack(side="right", padx=5)
        
        self.select_all_var = tk.BooleanVar()
        select_all_btn = tk.Checkbutton(batch_frame, text="全选", variable=self.select_all_var,
                                       command=self.toggle_select_all, bg="#34495e", fg="white",
                                       selectcolor="#34495e")
        select_all_btn.pack(side="left", padx=5)
        
        remove_btn = tk.Button(batch_frame, text="批量移除", command=self.batch_remove,
                             bg="#e74c3c", fg="white")
        remove_btn.pack(side="left", padx=5)
        
        tag_btn = tk.Button(batch_frame, text="批量添加标签", command=self.batch_add_tags,
                          bg="#f39c12", fg="white")
        tag_btn.pack(side="left", padx=5)
        
        # 主程序区
        main_frame = tk.Frame(self.root, bg="#2c3e50")
        main_frame.pack(fill="both", expand=True, padx=10, pady=(0, 10))
        
        # 漫画展示区
        self.comic_canvas = tk.Canvas(main_frame, bg="#2c3e50", highlightthickness=0)
        self.scrollbar = ttk.Scrollbar(main_frame, orient="vertical", command=self.comic_canvas.yview)
        self.scrollable_frame = tk.Frame(self.comic_canvas, bg="#2c3e50")
        
        self.scrollable_frame.bind(
            "<Configure>",
            lambda e: self.comic_canvas.configure(
                scrollregion=self.comic_canvas.bbox("all")
            )
        )
        
        self.comic_canvas.create_window((0, 0), window=self.scrollable_frame, anchor="nw")
        self.comic_canvas.configure(yscrollcommand=self.scrollbar.set)
        
        self.comic_canvas.pack(side="left", fill="both", expand=True)
        self.scrollbar.pack(side="right", fill="y")
        
        # 分页控件
        page_frame = tk.Frame(self.root, bg="#2c3e50", height=40)
        page_frame.pack(fill="x", padx=10, pady=(0, 10))
        
        self.prev_btn = tk.Button(page_frame, text="上一页", command=self.prev_page,
                                bg="#7f8c8d", fg="white", state="disabled")
        self.prev_btn.pack(side="left", padx=5)
        
        self.page_label = tk.Label(page_frame, text="第1页", bg="#2c3e50", fg="white")
        self.page_label.pack(side="left", padx=5)
        
        self.next_btn = tk.Button(page_frame, text="下一页", command=self.next_page,
                                bg="#7f8c8d", fg="white")
        self.next_btn.pack(side="left", padx=5)
        
        # 介绍栏
        info_frame = tk.LabelFrame(self.root, text="漫画详情", bg="#34495e", fg="white", padx=10, pady=10)
        info_frame.pack(fill="x", padx=10, pady=(0, 10))
        
        self.comic_name = tk.Label(info_frame, text="未选中漫画", bg="#34495e", fg="#3498db",
                                 font=("Arial", 12, "bold"))
        self.comic_name.pack(anchor="w", pady=(0, 5))
        
        self.comic_tags = tk.Label(info_frame, text="标签: 无", bg="#34495e", fg="#ecf0f1",
                                  font=("Arial", 10))
        self.comic_tags.pack(anchor="w")
        
        self.comic_path = tk.Label(info_frame, text="路径: 无", bg="#34495e", fg="#bdc3c7",
                                 font=("Arial", 9))
        self.comic_path.pack(anchor="w")
        
        # 右键菜单
        self.context_menu = tk.Menu(self.root, tearoff=0)
        self.context_menu.add_command(label="阅读漫画", command=read_comic)
        self.context_menu.add_command(label="设置标签", command=self.set_tags)
        self.context_menu.add_command(label="移除漫画", command=self.remove_comic)
        
        # 绑定鼠标滚轮事件
        self.comic_canvas.bind_all("<MouseWheel>", self._on_mousewheel)


    def load_comics(self, search_query=None, search_type="按名称"):
        # 清空当前显示
        for widget in self.scrollable_frame.winfo_children():
            widget.destroy()
        
        # 计算分页
        offset = (self.current_page - 1) * self.per_page
        
        # 查询数据库
        query = "SELECT id, name, folder_path, cover_path FROM comics"
        params = []
        
        if search_query:
            if search_type == "按名称":
                query += " WHERE name LIKE ?"
                params.append(f"%{search_query}%")
            elif search_type == "按标签":
                query = """
                    SELECT c.id, c.name, c.folder_path, c.cover_path 
                    FROM comics c
                    JOIN comic_tags ct ON c.id = ct.comic_id
                    WHERE ct.tag_name LIKE ?
                """
                params.append(f"%{search_query}%")
        
        query += " LIMIT ? OFFSET ?"
        params.extend([self.per_page, offset])
        
        self.cursor.execute(query, params)
        comics = self.cursor.fetchall()
        
        # 显示漫画
        row_frame = None
        for i, comic in enumerate(comics):
            comic_id, name, folder_path, cover_path = comic
            
            if i % 5 == 0:
                row_frame = tk.Frame(self.scrollable_frame, bg="#2c3e50")
                row_frame.pack(fill="x", pady=5)
            
            # 漫画项容器
            item_frame = tk.Frame(row_frame, bg="#34495e", padx=5, pady=5)
            item_frame.pack(side="left", padx=10)
            
            # 复选框
            var = tk.BooleanVar()
            chk = tk.Checkbutton(item_frame, variable=var, bg="#34495e", 
                               command=lambda cid=comic_id, v=var: self.toggle_comic(cid, v))
            chk.pack(anchor="nw")
            
            # 封面
            try:
                img = Image.open(cover_path)
                img.thumbnail((120, 180))
                photo = ImageTk.PhotoImage(img)
                
                cover_label = tk.Label(item_frame, image=photo, bg="#34495e", 
                                     cursor="hand2", relief="raised", bd=2)
                cover_label.image = photo
                cover_label.pack()
                
                # 绑定事件
                cover_label.bind("<Button-1>", lambda e, cid=comic_id: self.select_comic(cid))
                cover_label.bind("<Button-3>", lambda e, cid=comic_id: self.show_context_menu(e, cid))
            except:
                # 使用默认封面
                default_label = tk.Label(item_frame, text="封面缺失", width=15, height=8, 
                                       bg="#7f8c8d", fg="white", relief="raised", bd=2)
                default_label.pack()
                default_label.bind("<Button-1>", lambda e, cid=comic_id: self.select_comic(cid))
                default_label.bind("<Button-3>", lambda e, cid=comic_id: self.show_context_menu(e, cid))
            
            # 漫画名称
            name_label = tk.Label(item_frame, text=name, bg="#34495e", fg="white", 
                                cursor="hand2", wraplength=120)
            name_label.pack()
            name_label.bind("<Button-1>", lambda e, cid=comic_id: self.select_comic(cid))
            name_label.bind("<Button-3>", lambda e, cid=comic_id: self.show_context_menu(e, cid))
            
            # 记录复选框状态
            self.comic_checkboxes[comic_id] = var
            
        # 更新分页按钮状态
        self.update_pagination()
        
        # 重置选中状态
        self.selected_comics.clear()
        self.select_all_var.set(False)